//
//  TextBox.m
//  AHTest
//
//  Created by ash on 16/8/2.
//  Copyright © 2016年 ash. All rights reserved.
//

#import "TextBox.h"
#define kPlaceholderX 8
#define kPlaceholderY 8
//@interface PHTextView ()
//{
//      UILabel *placeholderLabel;
//}
////@property (nonatomic, assign) BOOL showCount;
//@end
//@implementation PHTextView
//- (id)initWithFrame:(CGRect)frame
//{
//    self = [super initWithFrame:frame];
//    if (self) {
//
//        [self setup];
//    }
//    return self;
//}
//
//-(instancetype)init{
//    if (self = [super init]) {
//        [self setup];
//    }
//    return self;
//}
//
//-(instancetype)initWithCoder:(NSCoder *)aDecoder{
//    if (self = [super initWithCoder:aDecoder]) {
//        [self setup];
//    }
//    return self;
//}
//-(void)awakeFromNib
//{
//    [super awakeFromNib];
//    [self setup];
//}
//- (void)setup {
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChangeNotification:) name:UITextViewTextDidChangeNotification object:self];
//    
//    //float left=5,top=8,hegiht=0;
//    
//    currentLine = 1;
////    [[NSNotificationCenter defaultCenter] addObserver:self
////                                             selector:@selector(didReceiveTextDidChangeNotification:)
////                                                 name:UITextViewTextDidChangeNotification
////                                               object:self];
////    
////    _placeholderColor = [UIColor lightGrayColor];
////    self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
////    self.scrollIndicatorInsets = UIEdgeInsetsMake(10.0f, 0.0f, 10.0f, 0.0f);
//    //self.contentInset = UIEdgeInsetsZero;
////    self.scrollEnabled = YES;
////    self.scrollsToTop = NO;
//    //self.userInteractionEnabled = YES;
//    //self.font = [UIFont systemFontOfSize:16.0f];
//    //self.textColor = [UIColor blackColor];
//    //self.backgroundColor = [UIColor whiteColor];
////    self.keyboardAppearance = UIKeyboardAppearanceDefault;
////    self.keyboardType = UIKeyboardTypeDefault;
////    self.returnKeyType = UIReturnKeyDefault;
////    self.textAlignment = NSTextAlignmentLeft;
//    //self.textContainer.lineBreakMode = NSLineBreakByCharWrapping;
//    //self.layoutManager.allowsNonContiguousLayout = NO;//UITextView 中的 layoutManager(NSLayoutManager) 的是否非连续布局属性，默认是 YES，设置为 NO 后 UITextView 就不会再自己重置滑动了
//    //self.delegate = self;
//}
//-(void)layoutSubviews{
//    [super layoutSubviews];
//     [placeholderLabel sizeToFit];
//
//    if (_verticalCenterPlaceholder) {
//         placeholderLabel.frame=CGRectMake(8, (self.height-CGRectGetHeight(placeholderLabel.frame))/2, CGRectGetWidth(self.frame)-16, CGRectGetHeight(placeholderLabel.frame));
//    }else{
//        placeholderLabel.frame=CGRectMake(8, 8, CGRectGetWidth(self.frame)-16, CGRectGetHeight(placeholderLabel.frame));
//    }
//   
//}
//-(void)setPlaceholderFont:(UIFont *)placeholderFont
//{
//    _placeholderFont=placeholderFont;
//    placeholderLabel.font=placeholderFont;
//}
//-(void)setFont:(UIFont *)font
//{
//    [super setFont:font];
//    placeholderLabel.font=self.placeholderFont?self.placeholderFont:self.font;
//}
//-(void)setPlaceholderColor:(UIColor *)placeholderColor
//{
//    _placeholderColor=placeholderColor;
//    placeholderLabel.textColor=placeholderColor;
//}
//-(void)setPlaceholder:(NSString *)placeholder{
//      _placeholder=placeholder;
//    if (placeholderLabel == nil){
//        placeholderLabel=[[UILabel alloc] init];
//        //placeholderLabel.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
//        placeholderLabel.lineBreakMode = NSLineBreakByWordWrapping;
//        placeholderLabel.textColor=[UIColor lightGrayColor];
//        placeholderLabel.font=self.font;
//        placeholderLabel.backgroundColor = [UIColor clearColor];
//        placeholderLabel.numberOfLines = 0;
//        if (_horizontalCenterPlaceholder) {
//            placeholderLabel.textAlignment=NSTextAlignmentCenter;
//        }
//        [self addSubview:placeholderLabel];
//    }
//        placeholderLabel.text=_placeholder;
//
//    [self refreshPlaceholder];
//}
//-(void)setText:(NSString *)text
//{
//    [super setText:text];
//    [self textDidChangeNotification:nil];
//}
//-(void)setHorizontalCenterPlaceholder:(BOOL)horizontalCenterPlaceholder{
//    _horizontalCenterPlaceholder=horizontalCenterPlaceholder;
//    if (_horizontalCenterPlaceholder) {
//        self.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
//        placeholderLabel.textAlignment=NSTextAlignmentCenter;
//    }
//}
//-(void)setVerticalCenterPlaceholder:(BOOL)verticalCenterPlaceholder{
//    _verticalCenterPlaceholder=verticalCenterPlaceholder;
//    if (_verticalCenterPlaceholder) {
//        
//    }
//}
//-(void)textDidChangeNotification:(NSNotification*)notification{
//    
//    [self refreshPlaceholder];
//    
//    NSInteger lines = self.contentSize.height / self.font.lineHeight;
//    if (self.maxLines && lines > self.maxLines) {
//        return;
//    }
//    
//    if (currentLine != lines && self.changeLineBlock) {
//        currentLine = lines;
//        self.changeLineBlock(lines);
//    }
//}
//-(void)refreshPlaceholder{
//    if (self.text.length > 0) {
//        placeholderLabel.hidden=YES;
//    }
//    else{
//        placeholderLabel.hidden=NO;
//    }
//}
//
//-(NSInteger)textLines{
//    return self.contentSize.height / self.font.lineHeight;
//}
//
//- (void)dealloc {
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}
//
//@end


@interface TextBox()<UITextViewDelegate,UITextFieldDelegate>
@property (nonatomic, assign) BOOL isLimitMode;
@end

@implementation TextBox

//- (instancetype)initWithMaxNumber:(NSInteger)maxNumber
//{
//    if (self = [super init]) {
//
//        [self buildUI];
//    }
//    return self;
//}
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //默认不受限制
        _isLimitMode = NO;
        _maxNumber = NSIntegerMax;
        [self buildUI];
        [self setupLayout:frame];
    }
    return self;
}
- (instancetype)init
{
    if (self = [super init]) {
        _isLimitMode = NO;
        _maxNumber = NSIntegerMax;
        [self buildUI];
    }
    return self;
}
#pragma ------setter---------
- (void)setTextBoxType:(TextBoxType)textBoxType {
    _textBoxType = textBoxType;
    [self buildUI];
    [self setupLayout:self.frame];
}
- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    [self buildUI];
    [self setupLayout:frame];
}
- (void)setMaxNumber:(NSInteger)maxNumber {
    _maxNumber = maxNumber;
    if (_maxNumber>0) {
        _isLimitMode = YES;
    }else{
        _isLimitMode = NO;
        _maxNumber = NSIntegerMax;
    }
}
- (void)setShowCount:(BOOL)showCount {
    _showCount = showCount;
    [self buildUI];
}
- (void)setIsEditable:(BOOL)isEditable
{
    _isEditable = isEditable;
    if (_textBoxType == TextViewBox) self.textView.editable = _isEditable;
    if (_textBoxType == TextFieldBox) self.textField.enabled = _isEditable;
}

- (void)buildUI
{
    if (_textBoxType == TextViewBox) {
        [self addSubview:self.textView];
        if (_isLimitMode && _showCount) {
            [self addSubview:self.lbLimit];
            self.lbLimit.text = [self limitStringWithNumber:self.textView.text.length];
        }
    }
    if (_textBoxType == TextFieldBox) [self addSubview:self.textField];
}
#pragma ------getter---------
- (UITextView *)textView
{
    if (_textView  == nil) {
        _textView = [[PHTextView alloc] init];
        //_textView.showCount = _showCount;
        //_textView.backgroundColor = [UIColor whiteColor];
        //        if (_isLimitMode) {
        //        }
        //_textView.font = [AKUIDesign fontForTextView];
        _textView.delegate = self;
    }
    return _textView;
}
- (UITextField *)textField {
    if (_textField == nil) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeClick:) name:UITextFieldTextDidChangeNotification object:nil];
        _textField = [[UITextField alloc] init];
        _textField.delegate = self;
    }
    return _textField;
}

- (UILabel *)lbLimit
{
    if (_lbLimit == nil) {
        UILabel *lb = [[UILabel alloc] init];
        lb.backgroundColor = [UIColor clearColor];
        lb.font = [UIFont systemFontOfSize:12];
        lb.textColor = [UIColor lightGrayColor];
        //lb.textColor = [AKUIDesign textLightGrayColor];
        lb.textAlignment = NSTextAlignmentRight;
        _lbLimit = lb;
    }
    return _lbLimit;
}
- (void)setupLayout:(CGRect)rect {
    if (_textBoxType == TextViewBox) {
        if (_showCount) {
            self.textView.frame = CGRectMake(0, 0, rect.size.width,  rect.size.height - 19);
            self.lbLimit.frame = CGRectMake(8, rect.size.height - 19, rect.size.width - 16, 14);
        } else {
            self.textView.frame = CGRectMake(0, 0, rect.size.width,  rect.size.height);
        }
    }
    if (_textBoxType == TextFieldBox) self.textField.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
}
//- (void)setContentString:(NSString *)contentString
//{
//    _contentString = [contentString copy];
//    self.textView.text = contentString;
//    self.lbLimit.text = [self limitStringWithNumber:contentString.length];
//}

//- (NSString *)contentString
//{
//    _contentString = self.textView.text;
//    return _contentString;
//}
-(NSString *)text{
    if (_textBoxType == TextViewBox) return self.textView.text;
    if (_textBoxType == TextFieldBox) return self.textField.text;
    return nil;
}
- (NSString *)limitStringWithNumber:(NSInteger)number
{
    return [NSString stringWithFormat:@"%ld/%ld",(long)number,(long)_maxNumber];
}
#pragma mark ---------TextViewDelegate-------
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // AKDLog(@"range %@  text %@  lenth %lu",NSStringFromRange(range), text, (unsigned long)textView.text.length);
    if (range.length >= 1) {//删除的情况
        return YES;
    }
    
    if (range.location >= _maxNumber) {
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (_textDidChangeBlock) {
         _textDidChangeBlock(self);
    }
   
    NSString *content = textView.text;
    if (content.length>_maxNumber) {
        textView.text = [content substringToIndex:_maxNumber];
    }
    if (_isLimitMode && _showCount) {
        self.lbLimit.text = [self limitStringWithNumber:textView.text.length];
        //[self.lbLimit sizeToFit];
    }
}
#pragma mark ----TextFieldDelegate or Notification------
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //判断加上输入的字符，是否超过界限
    NSString *str = [NSString stringWithFormat:@"%@%@", textField.text, string];
    if (str.length >= _maxNumber)
    {
        //textField.text = [textField.text substringToIndex:TITLE_WORD_LIMIT];
        return NO;
    }
    return YES;
}
- (void)changeClick:(NSNotification *)notification {
    _textDidChangeBlock(self);
    UITextField *tf = (UITextField *)notification.object;
    //该判断用于联想输入
    if (tf.text.length > _maxNumber)
    {
        tf.text = [tf.text substringToIndex:_maxNumber];
    }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}
@end

